var doc = null;
function ajax()
{
    if (window.XMLHttpRequest) {
        try {
            doc = new XMLHttpRequest();
        } catch(e)  {}
    } else if (window.ActiveXObject) {
        try {
            doc = new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e)  {
            try {
                doc = new ActiveXObject('Microsoft.XMLHTTP');
            } catch(e)  {}
        }
    }
}//Ajax engine

function RefreshPage()
{
    window.location.href=window.location.href;
}

function FormatNumber(x)//Format Number (1.5 to 1.50)
{
    if (x=="")
    {
        return '0.00';
        //window.location.href=window.location.href;//If x is null
    }

    var f_x = parseFloat(x);
    if (isNaN(f_x))
    {
        return false;
    }
    var f_x = Math.round(x*100)/100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0)
    {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2)
    {
        s_x += '0';
    }
    return s_x;
}

function upDigit(n)
{
    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [ ['元', '万', '亿'], ['', '拾', '佰', '仟']  ];
    var head = n < 0? '欠': '';
    n = Math.abs(n);

    var s = '';

    for (var i = 0; i < fraction.length; i++)
    {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++)
    {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++)
        {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')  + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}



function DoingWindow(act,width,title)
{
    document.getElementById("MyWindowSection").style.width = width+'px';
    document.getElementById("windowName").innerHTML = title;
    $('#MyWindowSection').bPopup({
        contentContainer:'.windowContentDiv',
        follow:[true,false],
        loadUrl:'/doingWindow.php?'+act //Uses jQuery.load()
    });
}

///////////////////////////////////////////////////////////
function startCheckParking()
{
    var cat = $("#write").val();
    if (cat == '')
    {
        MessageAlertTimes('请输入您的车牌号码',1500);
        return false;
    }else{
        ajax();
        if (doc)
        {
            doc.open("GET", "/doingGet.php?action=PM_Search&pkey="+PKEY+"&carNumber="+cat+"&t="+Math.random(),false);
            doc.send(null);
            if (doc.readyState==4 && doc.status==200)
            {
                var Lyz = doc.responseText.split("@@");
                var Doi = eval('(' + Lyz[1] + ')');
                if (Doi.resultId == 0)
                {
                    $("#write").val("");
                    MessageAlertTimes(Doi.failedMsg,1500);
                    return false;
                }else{
                    if (Doi.resultNum == 1)
                    {
                        loadOrderDetailsSet(Doi.orderId);
                    }else{
                        loadOrderSimilarSet(cat);
                    }
                }
            }
        }
    }
    $("#write").val("");
}

function loadOrderDetailsSet(orderid)
{
    ajax();
    if (doc)
    {
        doc.open("GET", "/doingGet.php?action=PM_orderDetail&orderId="+orderid+"&t="+Math.random(),false);
        doc.send(null);
        if (doc.readyState==4 && doc.status==200)
        {
            var Lyz = doc.responseText.split("@@");
            $("#mainDivs").html(Lyz);

            setTimeout("RefreshPage()",60000);
        }
    }
}

function loadOrderSimilarSet(car)
{
    ajax();
    if (doc)
    {
        doc.open("GET", "/doingGet.php?action=PM_loadOrderSimilarSet&carNumber="+car+"&t="+Math.random(),false);
        doc.send(null);
        if (doc.readyState==4 && doc.status==200)
        {
            var Lyz = doc.responseText.split("@@");
            $("#mainDivs").html(Lyz);
        }
    }
}

function checkPriceUpdating(oid,uptime,ret)
{
    var PAYS = '<button id="paymentBtns" onClick="orderPaynow();" class="btn btn-block btn-paynow"><i class="fa fa-check-square-o"></i> 立即支付</button>';
    var OUTS = '<button id="gooutBtns" onClick="orderGooutnow();" class="btn btn-block btn-default"><i class="fa fa-check-square-o"></i> 立即出场</button>';
    var FNSS = '<button id="couponFinished" onClick="RefreshPage();" class="btn btn-block btn-couponfinish"><i class="fa fa-check-square-o"></i> 优惠完成</button>';

    ajax();
    var repeats = 0;
    if (doc)
    {
        doc.open("GET", "/doingGet.php?action=PM_orderPriceUpdating&orderid="+oid+"&uptime="+uptime+"&t="+Math.random(),false);
        doc.send(null);
        if (doc.readyState==4 && doc.status==200)
        {
            var Lyz = doc.responseText.split("@@");
            var Doi = eval('(' + Lyz[1] + ')');
            if (Doi.isUpdate == 0)
            {
                repeats = 1;
            }else if(Doi.isUpdate == 1){
                repeats = 0;
                var Price = '&yen;'+Doi.newPrice;
                $("#priceDiv").html(Price);
                $("#couponDiv").html(Doi.couponDesc);
                if ((Doi.newPrice*1) > 0)
                {
                    $("#btnAreaSet").html(PAYS);
                }else{
                    if (Doi.outWay == '15')
                    {
                        $("#btnAreaSet").html(OUTS);
                    }else{
                        $("#btnAreaSet").html(FNSS);
                    }
                }

            }else{
                RefreshPage();
            }
        }
    }

    if (repeats == 1)
    {
        ret ++;
        if (ret == 10)
        {
            //setRepostCoupons(oid);
            ret = 0;
            setTimeout("checkPriceUpdating('"+oid+"','"+uptime+"','"+ret+"')",1000);
        }else{
            setTimeout("checkPriceUpdating('"+oid+"','"+uptime+"','"+ret+"')",1000);
        }
    }
}

function setRepostCoupons(oid)
{
    if (doc)
    {
        doc.open("GET", "/doingGet.php?section=publicSection&action=rePostCoupon&orderid="+oid+"&t="+Math.random(),false);
        doc.send(null);
        if (doc.readyState==4 && doc.status==200)
        {
            //var Lyz = doc.responseText.split("@@");
            //$("#wechatPaycode").attr("src",Lyz[1]);
        }
    }
}

function startCheckCouponScan(oid)
{
    /*
     var newText = '<div class="len-qrcodes">' +
     '<form data-toggle="validator" class="form-horizontal" action="/doingPost.php" target="dosets" method="post">' +
     '<input class="input scanareas" autocomplete="off" id="scanCodeCheck" name="couponCodes" autofocus="autofocus" type="text" placeholder="" />' +
     '<input type="hidden" name="section" value="publicSection" />' +
     '<input type="hidden" name="action" value="couponCodes" />' +
     '<input type="hidden" name="orderId" id="put_orderid" value="" />' +
     '</form>' +
     '</div>' +
     '<div class="margin-top-xs-20" id="CouponTextset" style="color:#FFF;"></div>';
     var xxtt = '<iframe src="http://www.baidu.com"></iframe>';
     swal("请在下方扫描您的停车券", xxtt)
     */
    defaultForm = 'couponScanForms';
    $("#coupon_orderid").val(oid);
    $("#CouponTextset").html("");

    $('#fadeandscale').bPopup({
        modalClose: true,
        opacity: 0.6,
        positionStyle: 'fixed' //'fixed' or 'absolute'
    });

    setInterval("trysetFocus('scanCodeCheck')",1000);
    //$("#scanCodeCheck").focus();
}

function startVIPCardScan()
{
    $("#CouponTextVipvas").html("");

    $('#vipcardscale').bPopup({
        modalClose: true,
        opacity: 0.6,
        positionStyle: 'fixed' //'fixed' or 'absolute'
    });

    setInterval("trysetFocus('scanCodeCheckVIP')",1000);
    //$("#scanCodeCheck").focus();
}

function startVIPJifeng()
{
    $("#CouponTextJifenttext").html("");

    $('#vipcardscalejifeng').bPopup({
        modalClose: true,
        opacity: 0.6,
        positionStyle: 'fixed' //'fixed' or 'absolute'
    });

    setInterval("trysetFocus('scanCodeCheckVIPS')",1000);
    //$("#scanCodeCheck").focus();
}

function trysetFocus(id)
{
    $("#"+id).focus();
}

function forCouponText(vars)
{
    $("#CouponTextset").html(vars);
    $("#scanCodeCheck").val("");
    $("#scanCodeCheck").focus();
}

function checkCouponSuccess(oid,uptime,rept)
{
    $(".coupon_close").click();
    $("#scanCodeCheck").val("");
    $("#priceDiv").html('<span style="font-size:14px;color:#000;"><i class="fa fa-spin fa-refresh"></i> 费用更新中...</span>');
    checkPriceUpdating(oid,uptime,0);
}

function startPaymentNoCoupon()
{
    loadWechatPayment(thisOrderId);
    loadAlipayPayment(thisOrderId);
    $("#juanArea").hide();
    $("#freePayArea").hide();
    $("#needPayArea").show();
}

function orderPaynow()
{
    var newOrderId = orderIds;
    if (newOrderId != '')
    {
        if (doc)
        {
            doc.open("GET", "/doingGet.php?action=PM_choosePayment&orderid="+newOrderId+"&t="+Math.random(),false);
            doc.send(null);
            if (doc.readyState==4 && doc.status==200)
            {
                var Lyz = doc.responseText.split("@@");
                $("#mainDivs").html(Lyz[1]);

                loadWechatPayment(newOrderId);
                loadAlipayPayment(newOrderId);

                setTimeout("RefreshPage()",120000);
                checkingPayResulting(newOrderId)
            }
        }
    }
}

function orderGooutnow()
{
    var newOrderId = orderIds;
    if (newOrderId != '')
    {
        if (doc)
        {
            doc.open("GET", "/doingGet.php?action=PM_directGoOuts&orderid="+newOrderId+"&t="+Math.random(),false);
            doc.send(null);
            if (doc.readyState==4 && doc.status==200)
            {
                var Lyz = doc.responseText.split("@@");
                $("#mainDivs").html(Lyz[1]);
                setTimeout("RefreshPage()",6000);
            }
        }
    }
}

function finishedFace(newOrderId)
{
    if (newOrderId != '')
    {
        if (doc)
        {
            doc.open("GET", "/doingGet.php?action=PM_finishedpay&orderid="+newOrderId+"&t="+Math.random(),false);
            doc.send(null);
            if (doc.readyState==4 && doc.status==200)
            {
                var Lyz = doc.responseText.split("@@");
                $("#mainDivs").html(Lyz[1]);
                setTimeout("RefreshPage()",6000);
            }
        }
    }
}

function loadWechatPayment(oid)
{
    if (doc)
    {
        doc.open("GET", "/doingGet.php?action=PM_loadWechatPayment&orderid="+oid+"&t="+Math.random(),false);
        doc.send(null);
        if (doc.readyState==4 && doc.status==200)
        {
            var Lyz = doc.responseText.split("@@");
            $("#wechatPaycode").attr("src",Lyz[1]);
        }
    }
}

function loadAlipayPayment(oid)
{
    if (doc)
    {
        doc.open("GET", "/doingGet.php?action=PM_loadAlipayPayment&orderid="+oid+"&t="+Math.random(),false);
        doc.send(null);
        if (doc.readyState==4 && doc.status==200)
        {
            var Lyz = doc.responseText.split("@@");
            if (Lyz[1] != '000')
            {
                $("#aliPaycode").attr("src",Lyz[1]);
            }
        }
    }
}

function checkingPayResulting(oid)
{
    if (oid != '')
    {
        if (doc)
        {
            doc.open("GET", "/doingGet.php?action=checkingWechating&orderid="+oid+"&t="+Math.random(),false);
            doc.send(null);
            if (doc.readyState==4 && doc.status==200)
            {
                var Lyz = doc.responseText.split("@@");
                var Doi = eval('(' + Lyz[1] + ')');
                if (Doi.resultId == 1)
                {
                    finishedFace(oid);
                    isRe = 1;
                }else{
                    isRe = 0;
                }
            }
        }
    }

    if (isRe == 0)
    {
        setTimeout("checkingPayResulting('"+oid+"')",1000);
    }
}

function resetAllChecks()
{
    RefreshPage();
    /*
     $("#setReadIn").show();
     $("#setReadOut").hide();
     thisOrderId = '';
     $("#couponDivsPk").hide();
     $("#paymentArea").hide();
     $("#NopaymentArea").hide();
     $("#len-results").hide();
     $("#resetAllChecksDiv").hide();
     $("#carImageDiv").html("");
     $("#put_carnumber").html("");
     $("#put_starttime").html("");
     $("#put_parkingtime").html("");
     $("#put_coupondesc").html("");
     $("#put_parkingfee").html("");
     $(".len-backbtnse").click();
     */
}

function MessageAlertTimes(msg,times)
{
    $("#alertmsgtext").html(msg);
    $('#alertmsg').bPopup({
        easing: 'easeOutBack', //uses jQuery easing plugin
        speed: 450,
        transition: 'slideDown',
        autoClose: times
    });
}

function MessageAlert(msg)
{
    swal(msg);
}